
import random
import string
import redis
import json
import re

from datetime import datetime
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password,check_password
from django.db.models import Q
from zhdate import ZhDate

from learning_platform.settings import SECRET_KEY
from .models import *
from .utils import MyJwt
from .serializers import *


# 用户管理
class UserView(ViewSet):

    # 获取图片验证码
    def image_code(self, request, uuid):

        try:
            salt = "".join(random.sample(string.ascii_letters + string.digits, 4))
            img = ImageCaptcha()
            image = img.generate(salt)
            r = redis.Redis(host='localhost',db=0,port=6379)
            key = 'img_%s'%uuid
            r.set(key, salt, ex=60 * 5)
            return HttpResponse(image, content_type='image/png')
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 添加用户
    def register(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        name = request.data.get('name')
        mobile = request.data.get('mobile')
        clbum = request.data.get('clbum')
        teacher_id = request.data.get('teacher_id')
        role_id = request.data.get('role_id')

        try:
            users = UserModel.objects.filter(account=account, is_delete=False).first()
            if users:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '用户已存在'})
            role = RoleModel.objects.filter(id=role_id,is_delete=False)
            if not role:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'角色不存在'})


            pwd = make_password(password)
            data1 = {
                "account": account,
                "password": pwd,
                'clbum':clbum,
                'teacher':teacher_id,
                'role':role_id
            }
            print(clbum,data1)
            ser1 = UserSer(data=data1)
            if not ser1.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': ser1.errors})
            ser1.save()
            user = UserModel.objects.filter(account=account,password=pwd,role_id=role_id).first()
            data2 = {
                'name':name,
                'mobile':mobile,
                'user':user.id
            }
            ser2 = UserInfoSer(data=data2)
            if not ser2.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': ser2.errors})
            ser2.save()
            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg': f'服务器错误{e}'})

    # 登录`
    def login(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        image_code = request.data.get('code')
        uuid = request.data.get('uuid')
        try:

            user = UserModel.objects.filter(account=account, is_delete=False).first()
            if check_password(password, user.password):
                # 添加操作日志
                myjwt = MyJwt()
                ser = UserSer(user)

                key = 'img_%s' %uuid
                r = redis.Redis(host='localhost', db=0, port=6379)
                code = r.get(key)

                if code == None:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '图片验证码已过期'})

                if image_code.lower() != code.decode().lower():
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '图片验证码不正确'})

                

                return Response({
                    'code': status.HTTP_200_OK,
                    'msg': '登录成功',
                    'token': myjwt.encode({'id': user.id}),
                    'data': ser.data,
                })
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '用户名或密码错误'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 获取班级下所有用户
    def user_desc(self, request):
        clbum = request.data.get('clbum')

        try:
            user = UserModel.objects.filter(is_delete=False).all()
            if clbum:
                user = UserModel.objects.filter(clbum_id=clbum, is_delete=False).all()
            ser = UserSer(user, many=True)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':ser.data})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 获取个人信息
    def user_info(self, request, pk):

         try:
            user = UserModel.objects.filter(id=pk).first()
            user = UserSer(user)
            user = json.loads(json.dumps(user.data))
            userinfo = UserinfoModel.objects.filter(user_id=user['id']).first()
            userinfo = UserInfoSer(userinfo)
            userinfo = json.loads(json.dumps(userinfo.data))
            user['userinfo_list'] = userinfo
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':userinfo})
         except Exception as e:
             return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改个人信息
    def upd_user(self, request, pk):

        name = request.data.get('name')
        signature = request.data.get('signature')
        mobile = request.data.get('mobile')

        try:
            flag = UserinfoModel.objects.filter(name=name, is_delete=False).count()
            if flag != 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该姓名已存在'})

            info = UserinfoModel.objects.filter(id=pk, is_delete=False).first()
            user = UserModel.objects.filter(id=info.id).first()
            if not user:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'用户不存在'})

            userinfo = UserinfoModel.objects.filter(id=pk, is_delete=False)
            if name:
                userinfo.update(name=name)
            if signature:
                userinfo.update(signature=signature)
            if mobile:
                userinfo.update(mobile)
            return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 删除用户
    def del_user(self, request, pk):

        try:
            flag = UserModel.objects.filter(id=pk, is_delete=False).count()
            if flag == 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该用户不存在'})

            user = UserModel.objects.filter(id=pk, is_delete=False)
            user.update(is_delete=True)
            users = UserModel.objects.filter(id=pk,is_delete=True).first()
            userinfo = UserinfoModel.objects.filter(user_id=users.id)
            userinfo.update(is_delete=True)
            return Response({'code':status.HTTP_200_OK,'msg':'删除成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})


# 学校管理
class SchoolView(ViewSet):

    # 获取所有学校
    def school_desc(self, request):
        try:
            school = SchoolModel.objects.filter(is_delete=False).all()
            ser = SchoolSer(school, many=True)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':ser.data})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 添加学校
    def add_school(self, request):

        name = request.data.get('name')

        try:
            flag = SchoolModel.objects.filter(name=name, is_delete=False).count()
            if flag != 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'学校已存在'})

            SchoolModel.objects.create(name=name)
            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 获取学校详情
    def school_info(self, request, pk):

        try:
            school = SchoolModel.objects.filter(id=pk).first()
            school = SchoolSer(school)
            school = json.loads(json.dumps(school.data))
            clbum = ClbumModel.objects.filter(school_id=school['id']).all()
            clbum = ClbumSer(clbum, many=True)
            clbum = json.loads(json.dumps(clbum.data))
            school['clbum_list'] = clbum
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':school})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改学校
    def upd_school(self, request, pk):

        name = request.data.get('name')

        try:
            flag = SchoolModel.objects.filter(id=pk, is_delete=False).count()
            if flag == 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该学校不存在'})

            school = SchoolModel.objects.filter(name=name, is_delete=False).first()
            if school:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该学校已存在'})

            SchoolModel.objects.filter(id=pk, is_delete=False).update(name=name)
            return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 删除学校
    def del_school(self, request, pk):

        try:
            flag = SchoolModel.objects.filter(id=pk, is_delete=False).first()
            if flag == 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该学校不存在'})

            SchoolModel.objects.filter(id=pk, is_delete=False).update(is_delete=True)
            return Response({'code':status.HTTP_200_OK,'msg':'删除成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})


# 班级管理
class ClbumView(ViewSet):

    # 获取学校下的班级
    def clbum_desc(self, request):

        school_id = request.data.get('school_id')

        try:
            clbum = ClbumModel.objects.filter(is_delete=False).all()
            if school_id:
                school = SchoolModel.objects.filter(id=school_id,is_delete=False).first()
                if not school:
                    return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该学校不存在'})
                clbum = clbum.filter(school_id=school.id, is_delete=False).all()

            ser = ClbumSer(clbum, many=True)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':ser.data})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 添加班级
    def add_clbum(self, request):

        school_id = request.data.get('school_id')
        name = request.data.get('name')

        try:
            if school_id:
                school = SchoolModel.objects.filter(id=school_id,is_delete=False).first()
                if not school:
                    return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该学校不存在'})
            flag = ClbumModel.objects.filter(school_id=school.id,name=name, is_delete=False).first()
            if flag:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'班级已存在'})
            ClbumModel.objects.create(name=name, school_id=school.id)
            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 班级详情
    def clbum_info(self, request, pk):

        try:
            flag = ClbumModel.objects.filter(id=pk).count()
            if flag == 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'班级不存在'})

            clbum = ClbumModel.objects.filter(id=pk, is_delete=False).first()
            clbum = ClbumSer(clbum)
            clbum = json.loads(json.dumps(clbum.data))
            user = UserModel.objects.filter(clbum_id=clbum['id']).all()
            user = UserSer(user, many=True)
            user = json.loads((json.dumps(user.data)))
            clbum['user_list'] = user
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':clbum})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改班级
    def upd_clbum(self, request, pk):

        name = request.data.get('name')

        try:
            flag = ClbumModel.objects.filter(id=pk, is_delete=False).count()
            if flag == 0:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该班级不存在'})

            clbum = ClbumModel.objects.filter(name=name, is_delete=False).first()
            if clbum:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该班级已存在'})

            ClbumModel.objects.filter(id=pk, is_delete=False).update(name=name)
            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 删除班级
    def del_clbum(self, request, pk):

        try:
            flag = ClbumModel.objects.filter(id=pk, is_delete=False).first()
            if flag == 0:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该班级不存在'})

            ClbumModel.objects.filter(id=pk, is_delete=False).update(is_delete=True)
            return Response({'code': status.HTTP_200_OK, 'msg': '删除成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

# 问候语
class GreetingsView(ViewSet):

    # 获取问候语
    def greetings_desc(self, request):

        try:
            timing = datetime.now().hour
            greeting = GreetingsModel.objects.filter(Q(start_time__lte=timing) & Q(end_time__gte=timing)).all()
            greeting = GreetingSer(greeting, many=True)
            greeting = json.loads(json.dumps(greeting.data))
            dan = random.choice(greeting)
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':dan})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 获取节日问候语
    def fes_greeting_desc(self, request):

        try:
            timing1 = datetime.now().strftime('%Y-%m-%d')
            timing2 = timing1.split('-')
            timing3 = datetime(int(timing2[0]),int(timing2[1]),int(timing2[2]))
            date = ZhDate.from_datetime(timing3)
            greeting1 = FesGreetingsModel.objects.filter(date_type=1, is_delete=False).all()
            greeting1 = FesGreetingSer(greeting1, many=True)
            greeting1 = json.loads(json.dumps(greeting1.data))
            greeting2 = FesGreetingsModel.objects.filter(date_type=2, is_delete=False).all()
            greeting2 = FesGreetingSer(greeting2, many=True)
            greeting2 = json.loads(json.dumps(greeting2.data))

            date = str(date)

            for i in greeting1:
                if  timing1[5:] == i['holiday_date']:
                    return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':i})
            for j in greeting2:
                if date[7:] == j['holiday_date']:
                    return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':j})

            return Response({'code':status.HTTP_200_OK,'msg':'当前不是任何节日'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

# 消息
class MessageView(ViewSet):

    # 发送消息
    def add_message(self, request):
        id = request.data.get('id')
        user_id = request.data.get('user_id')
        name = request.data.get("name")

        try:
            list = UserModel.objects.filter(id=user_id, is_delete=False)
            if not list:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '没有此用户'})
            MessageModel.objects.create(interaction=name, user_id=id, users_id=user_id)
            return Response({'code': status.HTTP_200_OK, 'msg': '发送成功'})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

    # 接收消息
    def message_desc(self, request):

        id = request.data.get('id')

        try:
            msg = MessageModel.objects.filter(users_id=id, is_delete=False).all()
            # print("msg", msg.query)
            ser = MessageSer(msg, many=True)

            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': ser.data})
        except Exception as e:
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': f'服务器错误{e}'})

# 搜索记录
class SearchView(ViewSet):

    # 添加搜索记录
    def add_search(self, request):

        id = request.data.get('user_id')
        content = request.data.get('content')

        try:
            SearchModel.objects.create(content=content,user_id=id)
            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

# 菜单管理
class MenuView(ViewSet):

    # 根据角色获取菜单
    def menu_desc(self, request):

        user_id = request.query_params.get('user_id')

        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'没有该用户'})
            role = RoleMenuModel.objects.filter(role_id=user.role_id, is_delete=False).all()
            role = RoleMenuSer(role, many=True)
            role = json.loads(json.dumps(role.data))
            lst = []
            for i in role:
                menu = MenuModel.objects.filter(id=i['menu'], is_delete=False, menu=None).first()
                menu = MenuSer(menu)
                menu = json.loads(json.dumps(menu.data))
                lst.append(menu)
            for i in lst:
                lit = MenuModel.objects.filter(menu=i['id'], is_delete=False).all()
                lit = MenuSer(lit, many=True)
                lit = json.loads(json.dumps(lit.data))
                i['menu_list'] = lit
            return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':lst})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 添加菜单
    def add_menu(self, request):

        name = request.data.get('name')
        menu_url = request.data.get('menu_url')
        menu_id = request.data.get('menu_id')

        role_id = request.data.get('role_id')

        try:
            menu = MenuModel.objects.filter(name=name, is_delete=False).first()
            if menu:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'菜单已存在'})

            if menu_id:
                menu_per = MenuModel.objects.filter(id=menu_id, menu=None, is_delete=False).first()
                if not menu_per:
                    return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'该菜单不存在'})

            MenuModel.objects.create(name=name, menu_url=menu_url, menu=menu_id)
            menu_lst = MenuModel.objects.filter(name=name, menu_url=menu_url, menu=menu_id, is_delete=False).first()
            role = RoleModel.objects.filter(id=role_id).first()
            if not role:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'角色未存在'})
            RoleMenuModel.objects.create(role_id=role_id,menu_id=menu_lst.id)
            return Response({'code':status.HTTP_200_OK,'msg':'添加成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 修改菜单
    def upd_menu(self,request, pk):

        name = request.data.get('name')
        menu_url = request.data.get('menu_url')

        try:
            menu_lst = MenuModel.objects.filter(id=pk, is_delete=False)
            if not menu_lst:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '菜单不存在'})
            menu = MenuModel.objects.filter(name=name, is_delete=False).first()
            if menu:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'菜单已存在'})
            if name:
                menu_lst.update(name=name)
            if menu_url:
                menu_lst.update(menu_url=menu_url)
            return Response({'code':status.HTTP_200_OK,'msg':'修改成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

    # 删除菜单
    def del_menu(self, request, pk):

        try:
            menu = MenuModel.objects.filter(id=pk, is_delete=False)
            if not menu:
                return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'菜单不存在'})

            menu.update(is_delete=True)
            return Response({'code':status.HTTP_200_OK,'msg':'删除成功'})
        except Exception as e:
            return Response({'code':status.HTTP_500_INTERNAL_SERVER_ERROR,'msg':f'服务器错误{e}'})

